package com.ecreditpal.audio.tencentAiDemo;


import com.ecreditpal.audio.util.MyHttpClient;
import com.sun.net.httpserver.Headers;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.util.*;

@Slf4j
public class TencentAiDemo {
    private static String appid="1257035476";
    private static String projectid="1013976";
    private static String sub_service_type="1";
    private static String engine_model_type="8k_0";
    private static String res_text_format="0";
    private static String res_type="0";
    private static String voice_format="1";
    private static String secretid="AKIDvhGeqqlIpAJHCvnt9IFB1f8RaXUE7CRW";
    private static String timestamp=String.valueOf(System.currentTimeMillis()/1000L);
    private static String expired=String.valueOf(System.currentTimeMillis()/1000L+24*60*60);
    private static String nonce=String.valueOf(new Random().nextInt(100000000));
    private static String seq="0";
    private static String end="1";
    private static String timeout="10000";
    private static String source="0";
    private static String secretKey="6Y3OhokZHgBVebT1iNvJXkvzxpkZDgz8";
    private static String voice_id="123456788";

    public static String getUrl(String url){
        StringBuilder sb=new StringBuilder(url);
        sb.append("projectid="+projectid+"&sub_service_type="+sub_service_type+"&engine_model_type="+engine_model_type+
        "&res_text_format="+res_text_format+"&res_type="+res_type+"&voice_format="+voice_format+
        "&secretid="+secretid+"&timestamp="+timestamp+"&expired="+expired+"&nonce="+nonce+
        "&seq="+seq+"&end="+end+"&timeout="+timeout+"&source="+source+"&voice_id="+voice_id);
        return sb.toString();
    }
    private static String getAuthorization(){
        String u="POSTaai.qcloud.com/asr/v1/1257035476?";
        String url=getUrl(u);
        BASE64Encoder base64Encoder=new BASE64Encoder();
        String authorization=base64Encoder.encode(HMACSha1(url,secretKey).getBytes());
        return authorization;

    }
    public static String HMACSha1(String data, String key) {
        String result;
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes());
            result = (new BASE64Encoder()).encode(rawHmac);
        } catch (Exception e) {
            throw new Error("Failed to generate HMAC : " + e.getMessage());
        }
        return result;
    }
    private static byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static void main(String[] args) {
        System.out.println("1111==="+nonce);
        HttpClient httpClient =MyHttpClient.getHttpClient();
        HttpResponse response = null;
        System.out.println("111===="+getAuthorization());
        int length=getBytes("/Users/xuebinxu/Downloads/pp3.wav").length;
        System.out.println("222==="+length);
        HttpPost post = new HttpPost(getUrl("https://aai.qcloud.com/asr/v1/1257035476?"));
        try{
            post.setHeader("Host","aai.qcloud.com");
            post.setHeader("Authorization",getAuthorization());
            post.setHeader("Content-Type","application/octet-stream");
            /*post.setHeader("Content-Length",String.valueOf(length));*/
            /*post.addHeader("Content-Length",String.valueOf(length));*/
            /*post.setHeader("Content-Length",String.valueOf(length));*/
            post.setEntity(new StringEntity(new FileInputStream("/Users/xuebinxu/Downloads/pp3.wav").toString()));
            System.out.println("115========="+getUrl("https://aai.qcloud.com/asr/v1/1257035476?"));
            response = httpClient.execute(post);
            System.out.println("116===="+response.getEntity());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                EntityUtils.consume(response.getEntity());
            } else {
//                String charset = getContentCharSet(response.getEntity());
                log.info( EntityUtils.toString(response.getEntity(), "utf-8"));
            }
        } catch (Exception e) {
            log.error("error sending post request the request", e);
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e1) {
                    log.error("error getting the entity", e);
                }
            }
        }
        System.out.println("132====="+String.valueOf(response.getStatusLine().getStatusCode()));
        }


}































































































































